package com.banmajio.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.banmajio.entity.User;
import com.banmajio.mapper.UserMapper;
import com.banmajio.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper mapper;

	@Override
	@Transactional
	@Cacheable(value = "redisCache", key = "'redis_user_'+#id")
	public User getUser(Long id) {
		return mapper.getUser(id);
	}

	@Override
	@Transactional
	@CachePut(value = "redisCache", key = "'redis_user_'+#result.id")
	public User insertUser(User user) {
		user.setCreateTime(new Date());
		mapper.insertUser(user);
		return user;
	}

	@Override
	@Transactional
	@CachePut(value = "redisCache", condition = "#result != 'null'", key = "'redis_user_'+#id")
	public User updateUser(User user) {
		User oldUser = this.getUser(user.getId());
		if (oldUser == null) {
			return null;
		}
		mapper.updateUser(user);
		return user;
	}

	@Override
	@Transactional
	public List<User> findUsers(String username, String note, Date createtime) {
		return mapper.findUsers(username, note, createtime);
	}

	@Override
	@Transactional
	@CacheEvict(value = "redisCache", key = "'redis_user_'+#id", beforeInvocation = false)
	public int deleteUser(Long id) {
		return mapper.deleteUser(id);
	}

}
